<template>
  <div class="main">
    <div class="left">
      <template v-if="fileUrl">

        <el-image style="width: 100px; height: 50px" :src="fileUrl" fit="cover"></el-image>

      </template>
    </div>
    <div class="right" v-if="!disabled">
      <el-button type="primary" @click="open">签名</el-button>
    </div>
    <el-dialog :visible.sync="visible" title="签名方式" :width="visibleWidth" append-to-body>
      <el-card style="margin-top: 20px">
        <el-form ref="postForm" :model="postForm" :rules="rules" :label-position="labelPosition" label-width="120px">
          <el-form-item label="签名方式" prop="type">
            <el-radio-group v-model="postForm.type" @change="change">
              <el-radio label="0">在线签名</el-radio>
              <el-radio label="1">上传图片</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="签名" prop="fileUrl" v-if="postForm.type == '0'">
            <div class="signatureBox">
              <VueSignaturePad class="VueSignaturePad" width="240px" height="120px" ref="signaturePad"
                :options="options" />
              <div class="buttons">
                <el-button icon="el-icon-delete" circle @click="clear()"></el-button>

              </div>
            </div>



          </el-form-item>
          <el-form-item label="签名" prop="fileUrl" v-if="postForm.type == '1'">
            <cropper-image
              @uploadImgSuccess="handleUploadSuccess"
            >
            </cropper-image>
            <!-- <el-upload class="avatar-uploader" :action="server" accept=".jpg,.jepg,.png" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <div v-if="postForm.fileUrl">
                <el-image v-if="postForm.fileUrl" style="width: 100px; height: 50px" :src="postForm.fileUrl"
                  fit="cover"></el-image>

                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click.stop="handlePictureCardPreview()">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                </span>
              </div>

              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload> -->
          </el-form-item>
        </el-form>
      </el-card>
      <div style="margin-top: 20px">
        <el-button type="primary" @click="oper('1')">确定</el-button>
        <el-button type="" @click="oper('0')">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" width="300px" height="150px" append-to-body>
      <el-image style="width: 100%; height: 150px" :src="postForm.fileUrl" fit="cover"></el-image>

    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'

import VueSignaturePad from "vue-signature-pad";
import CropperImage from "@/components/signatureCropperImage/CropperImage.vue";
import {
  uploadImg,
} from "@/api/common.js";
Vue.use(VueSignaturePad);
import FileUpload from "@/components/FileUpload";

import MobileDetect from 'mobile-detect';
export default {
  props: {
    value: String,
    disabled: Boolean,
    listType: {
      type: String,
      default: "picture",
    },
  },
  components: {
    // VueSignaturePad
    CropperImage
  },

  watch: {
    // 检测查询变化
    value: {
      handler() {
        this.fillValue();
      },
    },
  },
  data() {
    return {
      server: `${process.env.VUE_APP_BASE_API}/common/api/file/upload`,
      options: {
        penColor: "#000",
        // backgroundColor: '#ddd',
        minWidth: 1,    //控制画笔最小宽度
        maxWidth: 1,    //控制画笔最大宽度
      },
      headers: {

      },
      visible: false,
      dialogVisible: false,
      fileUrl: "",
      postForm: {
        type: "",
        fileUrl: "",
      },
      rules: {
        type: [{ required: true, message: "请选择签名方式！" }],

        fileUrl: [{ required: true, message: "签名不能为空！" }],
      },
      visibleWidth:'600px',
      labelPosition: 'left'
    };
  },
  created() {
    this.fillValue();
    this.detectDevice();
  },

  methods: {
    detectDevice() {
      const md = new MobileDetect(window.navigator.userAgent);
      let deviceType = md.mobile() ? "Mobile" : (md.tablet() ? "Tablet" : "Desktop");
      if (deviceType == 'Mobile') {
        this.visibleWidth = '100%'
        this.labelPosition = 'top'
      } else {
        this.visibleWidth = '600px'
        this.labelPosition = 'left'
      }
    },
    change() {
      this.postForm.fileUrl = ''
    },
    async open() {
      this.visible = true;
      this.postForm.fileUrl = ''
      await this.$nextTick()
      this.$refs.postForm.resetFields()
      // if (this.fileUrl) {
      //   this.postForm.fileUrl = this.fileUrl
      //   if (this.fileUrl.includes('upload')) {
      //     this.postForm.type = '1'
      //   } else {
      //     this.postForm.type = '0'
      //   }
      // } else {
      //   await this.$nextTick()
      //   this.$refs.postForm.resetFields()
      // }
    },
    fillValue() {
      if (this.value) {
        this.fileUrl = this.value;

      } else {
        this.fileUrl = '';
      }

    },
    // handleAvatarSuccess(res, file) {
    //   console.log(file);
    //   this.postForm.fileUrl = res.data.url;
    // },
    handleUploadSuccess(url){
      this.postForm.fileUrl = url;
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = (file.type === "image/jpeg" || file.type === "image/png");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true;
    },
    // 文件上传成功时的钩子
    handleSuccess(response) {

      this.$emit("input", response.data.url);
    },
    //清除
    clear() {
      this.$refs.signaturePad.clearSignature();
    },
    dataURLtoBlob(dataurl, name) {//base64转file
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], name, {
        type: mime,
      })
    },
    //保存


     oper(key) {
      switch (key) {
        case "1":
          if (this.postForm.type == '0') {
            const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
            console.log(isEmpty, data);
            this.postForm.fileUrl = data;
            this.$refs.signaturePad.clearSignature();
          }
          this.$refs.postForm.validate(async(valid) => {
            if (!valid) {
              return;
            }

            
            if (this.postForm.type == '0') {
              let formData = new FormData()
              let file = this.dataURLtoBlob(this.postForm.fileUrl,'签名.png')
              console.log(file);
              formData.append('file',file );
              let res = await uploadImg(formData)
              this.postForm.fileUrl = res.data.url;
              
              console.log(res);
              this.$refs.signaturePad.clearSignature();
            }
            this.$emit('input', this.postForm.fileUrl)
            this.visible = false;
          });
          break;
        case "0":
          this.visible = false;
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  display: flex;
  justify-content: flex-start;

  .signature {
    width: 100px;
    height: 50px;
    // object-fit: contain;

  }

  .right {
    margin-left: 10px;
  }
}

/deep/ .el-form-item__content {
  line-height: 40px !important;
  position: relative;
  font-size: 14px;
}

/deep/ .avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 50px;
    line-height: 50px;
  }

  .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .avatar {
    width: 100px !important;
    height: 50px !important;
    display: block;
  }
}

/deep/ .el-upload-list__item-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: pointer;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;

  &:after {
    display: inline-block;
    content: "";
    height: 100%;
    vertical-align: middle;
  }

  span {
    cursor: pointer;
  }

  &:hover {
    opacity: 1;
  }
}

.signatureBox {
  width: 240px;


  .VueSignaturePad {
    border: 1px solid #e6ebf5;
    background-color: #FFFFFF;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    -webkit-transition: 0.3s;
    transition: 0.3s;
  }

  .buttons {
    margin-top: 10px;
  }
}
</style>